package com.doupi.partner.util;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;

/**
 * 分页对象
 * 
 * @author Super Jens Wang
 *
 * @version 1.0 @ 2016年7月20日 上午5:32:52
 */
public class Pagination<P, T> implements Serializable {

	private static final long serialVersionUID = -7590843676422286260L;

	/** 当前页码 */
	private int page;

	/** 总条数 */
	private int totalCount;

	/** 总页码数 */
	private int pageCount;

	/** 偏移量 */
	private int offset;

	/** 取条数 */
	private int limit;

	/** 查询参数 */
	private P param;

	/** 返回记录数 */
	private List<T> records;

	/**
	 * mysql的分页规则
	 *
	 * @param offset
	 *            偏移量
	 * @param limit
	 *            限制条数
	 * @param param
	 *            参数
	 */
	public Pagination(int offset, int limit, P param) {
		this.offset = offset;
		this.limit = limit;
		if (this.limit <= 0) {
			this.limit = Integer.MAX_VALUE;
		}
		this.param = param;
		this.page = (this.offset / this.limit) + 1;
	}

	/**
	 * 正常分页规则
	 *
	 * @param param
	 *            参数
	 * @param page
	 *            页码
	 * @param limit
	 *            每页条数
	 */
	public Pagination(P param, int page, int limit) {
		this.param = param;
		this.page = page;
		this.limit = limit;
		if (this.limit <= 0) {
			this.limit = Integer.MAX_VALUE;
		}
		this.offset = this.limit * (this.page - 1);
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getTotalCount() {
		return totalCount;
	}

	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}

	public int getPageCount() {
		return pageCount;
	}

	public void setPageCount(int pageCount) {
		this.pageCount = pageCount;
	}

	public int getOffset() {
		return offset;
	}

	public void setOffset(int offset) {
		this.offset = offset;
	}

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public P getParam() {
		return param;
	}

	public void setParam(P param) {
		this.param = param;
	}

	public List<T> getRecords() {
		if (records == null) {
			records = Collections.emptyList();
		}
		return records;
	}

	public void setRecords(List<T> records) {
		this.records = records;
	}

	@Override
	public int hashCode() {
		return HashCodeBuilder.reflectionHashCode(this);
	}

	@Override
	public boolean equals(Object obj) {
		return EqualsBuilder.reflectionEquals(this, obj);
	}

	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
	}

}
